import json
import os
import uuid
from operator import itemgetter, attrgetter

from flask import Blueprint, url_for, flash, request, jsonify, current_app, \
    send_from_directory
from flask_jwt_extended import create_access_token, jwt_required
from flask_login import login_user, logout_user, login_required, current_user
from sqlalchemy.sql.elements import and_
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename

from application import db

from application.users.models import Users, Role, UsersRole, RolePermission
from application.users.schemas import UsersSchema, RoleSchema, UsersRoleSchema, PermissionSchema, RolePermissionSchema
from application.common.file_helper import allowed_pic_file, get_root_path

users_api = Blueprint('users_api', __name__)


# 角色列表
@users_api.route('/role', methods=['GET'])
def role():
    # 角色id, name,code
    get_user = Role.query.all()
    users_schema = RoleSchema(many=True, only=('id', 'name', 'code'))
    role = users_schema.dump(get_user)
    return jsonify({'status_code': 200, 'status_message': '成功', 'data': role})


# 角色详情
@users_api.route('/role', methods=['GET'])
def role():
    # 角色id, name,拥有该角色的用户,改角色拥有的权限
    get_user = Role.query.all()
    users_schema = RoleSchema(many=True)
    role = users_schema.dump(get_user)

    return jsonify({'status_code': 200, 'status_message': '成功', 'data': role})

# 增加角色
@users_api.route('/create_role', methods=['POST'])
def create_role():
    # 从请求里面获取json数据
    json_data_str = request.get_data(as_text=True)
    json_data = json.loads(json_data_str)
    roles_schema = RoleSchema()
    # 将json数据转换成model
    role = roles_schema.load(json_data)
    db.session.add(role)
    db.session.commit()
    user = roles_schema.dump(role)
    return jsonify({'status_code': 200, 'status_message': '成功', 'data': role})

# 修改角色信息(id不能改)
@users_api.route('/update_role/<int:id>', methods=['PATCH'])
def update_role(id):
    json_data = request.get_json()

    get_role = Role.query.get(id)
    if 'name' in json_data:
        get_role.fullname = json_data['name']
    if 'code' in json_data:
        get_role.status = json_data['code']
    db.session.add(get_role)
    db.session.commit()

    users_schema = RoleSchema()
    # 将json数据转换成model
    role = users_schema.dump(get_role)
    return jsonify({'status_code': 200, 'status_message': '成功', 'data': role})


# 删除角色
@users_api.route('/delete_role/<int:id>', methods=['DELETE'])
def delete_role(id):
    role = Role.query.get(id)
    db.session.delete(role)
    db.session.commit()
    return jsonify({'status_code': 200, 'status_message': '成功', 'id': role.id})


# 取用户拥有的角色
@users_api.route('/user_role/<int:user_id>', methods=['GET'])
def user_role(user_id):
    get_user = Users.query.get(user_id)
    get_roles = get_user.role.all()
    user_role_schema = UsersRoleSchema(many=true)
    roles = user_role_schema.dump(get_roles)
    return jsonify({'status_code': 200, 'status_message': '成功', 'data': roles})

# 给用户分配或者取消角色
@users_api.route('/is_distribution_role/<int:user_id>', methods=['POST', 'DELETE'])
def is_distribution_role(user_id):
    json_data_str = request.get_data(as_text=True)
    json_data = json.loads(json_data_str)
    type = request.method
    codes = json_data['code']
    if type == 'POST':
        for code in codes:
            new_role = {'role_id': code, 'user_id': user_id}
            user_role_schema = UsersRoleSchema()
            uer_role = user_role_schema.load(new_role)
            db.session.add(uer_role)
            db.session.commit()
        return jsonify({'status_code': 200, 'status_msg': '添加成功', 'id': user_id})
    elif type == 'GET':
        for code in codes:
            print(user_id)
            get_user_role = UsersRole.query.filter(
                and_(UsersRole.user_id == user_id, UsersRole.role_id == code)).first()
            print(get_user_role)
            db.session.delete(get_user_role)
            db.session.commit()
        return jsonify({'status_code': 200, 'status_msg': '删除成功', 'id': user_id})


# 该角色拥有的权限详情
@users_api.route('/role_permission/<int:role_id>', methods=['GET'])
def role_permission(role_id):
    get_role_by_id = Role.query.get(role_id)
    get_permission = get_role_by_id.permission.all()
    permission_schema = PermissionSchema()
    permission = permission_schema.dump(get_permission)
    return jsonify({'status_code': 200, 'status_message': '成功', 'data': permission})


# 给角色添加权限或取消权限
@users_api.route('/is_distribution_permission/<int:role_id>', methods=['POST', 'DELETE'])
def is_distribution_role(role_id):
    json_data_str = request.get_data(as_text=True)
    json_data = json.loads(json_data_str)
    type = request.method
    codes = json_data['code']

    if type == 'POST':
        for code in codes:
            new_permission = {'role_id': role_id, 'permission': code}
            role_permission = RolePermissionSchema()
            permission_role = role_permission.load(new_permission)
            db.session.add(permission_role)
            db.session.commit()
        return jsonify({'status_code': 200, 'status_msg': '添加成功', 'id': role_id})
    elif type == 'DELETE':
        for code in codes:
            get_permission_role = RolePermission.query.filter(
                and_(RolePermission.role_id == role_id, RolePermission.permission_id == code)).first()
            db.session.delete(get_permission_role)
            db.session.coomit()
        return jsonify({'status_code': 200, 'status_msg': '删除成功', 'id': role_id})



